package com.howie.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.howie.common.to.es.SkuEsModel;
import com.howie.gulimall.search.config.GulimallElasticSearchConfig;
import com.howie.gulimall.search.constant.EsConstant;
import com.howie.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: laizhenghua
 * @date: 2021/1/23 10:22
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> models) throws IOException {
        // 把商品信息保存到es
        // 1、在es中创建保存商品的索引与映射关系(执行product_mapping.txt脚本)
        // 2、使用bulk(BulkRequest bulkRequest, RequestOptions options)批量保存数据
        BulkRequest bulkRequest = new BulkRequest();
        models.forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); // 指定是product索引
            indexRequest.id(String.valueOf(skuEsModel.getSkuId())); // 设置唯一id
            String jsonSkuEsModel = JSON.toJSONString(skuEsModel); // 把SkuEsModel转为json字符串
            indexRequest.source(jsonSkuEsModel, XContentType.JSON); // 构造保存请求
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        // TODO: 如果批量保存错误，进行错误处理
        boolean isError = bulk.hasFailures(); // 失败就返回true
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());

        log.info("商品上架完成：{}，返回数据：{}",collect,bulk.toString());

        return isError;
    }
}
